import 'package:dio/dio.dart';
import 'package:sonora/services/sj_api_client.dart';
import 'package:sonora/utils/sj_device_utils.dart';

class SjApiService {
  final SjApiClient _client;

  SjApiService._internal(this._client);

  static final SjApiService _instance = SjApiService._internal(
    SjApiClient(getDefaultDio())
  );

  factory SjApiService() {
    return _instance;
  }

  SjApiClient get client => _client;

  static Dio getDefaultDio() {
    Dio dio = Dio();
    dio.interceptors.add(LogInterceptor(
      request: true,
      requestHeader: true,
      responseHeader: true,
      responseBody: true,
      error: true
    ));

    dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) async {
        final headers = await _buildHeaders();
        options.headers.addAll(headers);
        return handler.next(options);
      },
      onError: (error, handler) {
        return handler.next(error);
      },
    ));
    return dio;
  }

  // 通用的header生成方法
  static Future<Map<String, String>> _buildHeaders() async {
    // final token = await _getToken();
    final deviceId = await SjDeviceUtils.getUdid();
    final platform = await SjDeviceUtils.getPlatform();
    final model = await SjDeviceUtils.getDeviceModel();
    final pkg = await SjDeviceUtils.getPackageName();
    final ver = await SjDeviceUtils.getAppVersion();
    final p_ver = await SjDeviceUtils.getBuildNumber();
    final kst = '1';
    final sys_lan = await SjDeviceUtils.getSystemLanguage();
    final lang = await SjDeviceUtils.getSystemLanguage();

    return {
      'Content-Type': 'application/json',
      'device-id': deviceId!,
      'platform': platform,
      'model': model,
      'pkg': pkg,
      'ver': ver,
      'p_ver': p_ver,
      'kst': kst,
      'sys_lan': sys_lan,
      'lang': lang,
    };
  }
}